/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.GssDroid;
import gr.ebs.gssdroid.GssDroidApplication;
import gr.ebs.gssdroid.R;

import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.security.cert.X509Certificate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GssLogin extends Activity {
	private static final String LOGIN_URL="https://pithos.grnet.gr/pithos/login";
	//private static final String LOGIN_URL="http://192.168.0.2:8080/pithos/login";
	private String token = null;
	private String username=null;
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			final WebView webview = (WebView) findViewById(R.id.browser);
			if (webview.canGoBack()) {
				webview.goBack();
				return true;
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	public void onBackPressed() {
		final WebView webview = (WebView) findViewById(R.id.browser);
		if (webview.canGoBack())
			webview.goBack();
		/*
		 * else super.onBackPressed();
		 */
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final GssDroidApplication app = getDroidApp();
		setContentView(R.layout.login);
		
		if(GssDroid.useSavedData)
			if (!app.getPreferences().hasData()) {
				Intent intent = new Intent(getApplication(), GssSettings.class);
				startActivity(intent);
				// close out this activity
				finish();
			}
		/*if(getIntent().getExtras()!=null&&getIntent().getExtras().getString("login")!=null &&
				getIntent().getExtras().getString("token")!=null){
			Intent intent = new Intent(getApplication(), GssMyFolders.class);
			startActivity(intent);
			// close out this activity
			finish();
		}*/
		CookieSyncManager.createInstance(this);
		CookieSyncManager.getInstance().startSync();
		//accept self signed certificates
		try {
			 HostnameVerifier utv = new HostnameVerifier() {
				
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			};
			 HttpsURLConnection.setDefaultHostnameVerifier(utv);
			 SSLContext context = SSLContext.getInstance("TLS") ;
			 TrustManager[] myTrustmangers = new TrustManager[1];
			 myTrustmangers[0]=new NulledTrustManager();
			 context.init(null,myTrustmangers, new SecureRandom());
			 
			 HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 


		final WebView webview = (WebView) findViewById(R.id.browser);//new WebView(this);
		webview.getSettings().setJavaScriptEnabled(true);
		// webview.setHttpAuthUsernamePassword("vho.grnet.gr", "VHO login",
		// "ebs-koutsoub", "mwJBdgbtv");
		
		webview.clearCache(true);
		webview.clearFormData();
		webview.clearHistory();
		
		webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		webview.getSettings().setBuiltInZoomControls(true);
		//webview.getSettings().setDefaultZoom(ZoomDensity.);
		if(Build.VERSION.SDK_INT!=7)
			webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

		webview.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
		          handler.proceed();
		     }

			  @Override public boolean shouldOverrideUrlLoading(WebView view,
			  String url) { 
				  view.loadUrl(url); return true;
			  }
			 
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				webview.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			}

			@Override
			public void onReceivedHttpAuthRequest(WebView view,
					final HttpAuthHandler handler, String host, String realm) {
				String[] up = view.getHttpAuthUsernamePassword(host, realm);
				if (up != null && up.length == 2) {
					handler.proceed(up[0], up[1]);
					
				} else {
					if(GssDroid.useSavedData)
						handler.proceed(app.getPreferences().getUsername(), app.getPreferences().getPassword());
					else{
						final AlertDialog.Builder alert = new AlertDialog.Builder(GssLogin.this);
			        	alert.setTitle("Pithos Login");
			        	//View lv = findViewById(R.layout.dialoglogin);
			        	//alert.setView(lv);
			    		final EditText input = new EditText(GssLogin.this);//(EditText) lv.findViewById(R.id.username); 
			    		final EditText pass = new EditText(GssLogin.this);//(EditText) lv.findViewById(R.id.password);
			    		pass.setTransformationMethod(new PasswordTransformationMethod());
			    		LinearLayout layout = new LinearLayout(GssLogin.this);
			    		layout.setOrientation(LinearLayout.VERTICAL);
			    		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			    		layout.setLayoutParams(params);
			    		input.setLayoutParams(params);
			    		pass.setLayoutParams(params);
			    		TextView username = new TextView(GssLogin.this);
			    		username.setText("Username:");
			    		
			    		TextView password = new TextView(GssLogin.this);
			    		password.setText("Password:");
			    		layout.addView(username);
			    		layout.addView(input);
			    		layout.addView(password);
			    		layout.addView(pass);
			    		alert.setView(layout);
			    		
			    		alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
			    			public void onClick(DialogInterface dialog, int whichButton) {
			    				String uvalue = input.getText().toString().trim();
			    				String pvalue = pass.getText().toString().trim();
			    				handler.proceed(uvalue, pvalue);			    				
			    			}
			    		});

			    		alert.setNegativeButton("Cancel",
			    				new DialogInterface.OnClickListener() {
			    					public void onClick(DialogInterface dialog, int whichButton) {
			    						dialog.cancel();
			    					}
			    				});
			    		alert.show();
					}
				}

			}
		});
		
		//setContentView(webview);
		webview.loadUrl(LOGIN_URL);
	}

	class MyJavaScriptInterface {

		public void showHTML(String html) {
			token = getHtmlValue("Athentication token:", html);
			if(token!=null){
				username = getHtmlValue("Username:", html);
				if(username != null){
					
					getDroidApp().getPreferences().setLogin(username);
					getDroidApp().getPreferences().setToken(token);
					getDroidApp().getPreferences().save();
					startMainActivity();
					// close out this activity
					finish();
				}
			}
				
			
		}
	}
	
	private String getHtmlValue(String substring, String html){
		String result=null;
		boolean found = false;
		found = html.contains(substring);
		if (found) {
			int indx = html.indexOf(substring);
			StringBuffer res = new StringBuffer();
			for (int i = indx + substring.length(); i < html
					.length(); i++) {
				char c = html.charAt(i);
				if (c == '<')
					break;
				res.append(c);
			}

			result = res.toString();
			result = result.trim();
			
		} 
		return result;
	}
	
	public void startMainActivity( ){
		Intent intent =  new Intent(getApplication(), GssDroid.class);
		if(getIntent().getExtras()!=null && getIntent().getExtras().get("content")!=null)
			intent.putExtra("content", (Serializable)getIntent().getExtras().get("content"));
		startActivity(intent);
		GssLogin.this.finish();
	}
	
	public class NulledTrustManager implements TrustManager{ 
		   public boolean certificateCallback(X509Certificate[] o, int validateErr) {
		   /*System.out.println(" --- Do Not Use In Production ---\n" + 
		                          " By using this NulledTrustManager, the trust in" +
		                            " the server's identity is completely lost.\n" +                           " --------------------------------");
		                          */
		   //for (int i=0; i<o.length; i++)
		     //System.out.println(" certificate " + i + " -- " + o[i].toString());
		   return true;
		  }
		}
	public GssDroidApplication getDroidApp(){
		return (GssDroidApplication) getApplicationContext();
	}
	
}
